<?php
class sendmail
{
	function sendmail()
	{
		global $PHPCMS;
		$this->set($PHPCMS['mail_server'], $PHPCMS['mail_port'], $PHPCMS['mail_user'], $PHPCMS['mail_password'], $PHPCMS['mail_type']);
		$this->auth = 1;
	}

	function set($server, $port, $user, $password, $type = 1, $delimiter = 1, $mailusername = 0)
	{
		$this->type = $type;
		$this->server = $server;
		$this->port = $port;
		$this->user = $user;
		$this->password = $password;
        $this->delimiter = $delimiter == 1 ? "\r\n" : ($delimiter == 2 ? "\r" : "\n");
		$this->mailusername = $mailusername;
		//echo $this->type.' - '.$this->server.' - '.$this->port.' - '.$this->user.' - '.$this->password.' - '.$this->delimiter.' - '.$this->mailusername;
	}

	function send($email_to, $email_subject, $email_message, $email_from = '')
	{
		global $PHPCMS;
		//增加
		$email_subject = str_replace("\r", '', $email_subject);
		$email_message = str_replace("\r\n.", " \r\n..", str_replace("\n", "\r\n", str_replace("\r", "\n", str_replace("\r\n", "\n", str_replace("\n\r", "\r", $email_message)))));
		//注释掉
		/*
		$email_subject = '=?'.CHARSET.'?B?'.base64_encode(str_replace("\r", '', $email_subject)).'?=';
		$email_message = str_replace("\r\n.", " \r\n..", str_replace("\n", "\r\n", str_replace("\r", "\n", str_replace("\r\n", "\n", str_replace("\n\r", "\r", $email_message)))));
		$adminemail = $this->type == 1 ? $PHPCMS['mail_user'] : $PHPCMS['adminemail'];
		$email_from = $email_from == '' ? '=?'.CHARSET.'?B?'.base64_encode($PHPCMS['sitename'])."?= <$adminemail>" : (preg_match('/^(.+?) \<(.+?)\>$/',$email_from, $from) ? '=?'.CHARSET.'?B?'.base64_encode($from[1])."?= <$from[2]>" : $email_from);
		$emails = explode(',', $email_to);
		foreach($emails as $touser)
		{
			$tousers[] = preg_match('/^(.+?) \<(.+?)\>$/',$touser, $to) ? ($this->mailusername ? '=?'.CHARSET.'?B?'.base64_encode($to[1])."?= <$to[2]>" : $to[2]) : $touser;
		}
		$email_to = implode(',', $tousers);
		$headers = "From: $email_from{$this->delimiter}X-Priority: 3{$this->delimiter}X-Mailer: GoWayCN {$this->delimiter}MIME-Version: 1.0{$this->delimiter}Content-type: text/html; charset=".CHARSET."{$this->delimiter}";
		*/
		if($this->type == 1)
		{
			//修改调用
			//return $this->smtp($email_to, $email_subject, $email_message, $email_from, $headers);
			return $this->send_mail($email_to,$email_to,$email_subject,$email_message,1);
		}
		elseif($this->type == 2)
		{
			return @mail($email_to, $email_subject, $email_message, $headers);
		}
		else
		{
			ini_set('SMTP', $this->server);
			ini_set('smtp_port', $this->port);
			ini_set('sendmail_from', $email_from);
			return @mail($email_to, $email_subject, $email_message, $headers);
		}
	}
	/**
	 * 邮件发送
	 *
	 * @param: $name[string]        接收人姓名
	 * @param: $email[string]       接收人邮件地址
	 * @param: $subject[string]     邮件标题
	 * @param: $content[string]     邮件内容
	 * @param: $type[int]           0 普通邮件， 1 HTML邮件
	 * @param: $notification[bool]  true 要求回执， false 不用回执
	 *
	 * @return boolean
	 */
	function send_mail($name, $email, $subject, $content, $type = 0, $notification=false)
	{
	    	global $PHPCMS;
	        /* 邮件的头部信息 */
	        $content_type = ($type == 0) ?
	            'Content-Type: text/plain; charset=' . CHARSET : 'Content-Type: text/html; charset=' . CHARSET;
	        $content   =  base64_encode($content);
	
	        $headers = array();
	        $headers[] = 'Date: ' . gmdate('D, j M Y H:i:s') . ' +0000';
	        $headers[] = 'To: "' . '=?' . CHARSET . '?B?' . base64_encode($name) . '?=' . '" <' . $email. '>';
	        $headers[] = 'From: "' . '=?' . CHARSET . '?B?' . base64_encode($PHPCMS['sitename']) . '?='.'" <' . $PHPCMS['mail_user'] . '>';
	        $headers[] = 'Subject: ' . '=?' . CHARSET . '?B?' . base64_encode($subject) . '?=';
	        $headers[] = $content_type . '; format=flowed';
	        $headers[] = 'Content-Transfer-Encoding: base64';
	        $headers[] = 'Content-Disposition: inline';
	        if ($notification)
	        {
	            $headers[] = 'Disposition-Notification-To: ' . '=?' . CHARSET . '?B?' . base64_encode($PHPCMS['sitename']) . '?='.'" <' . $PHPCMS['mail_user'] . '>';
	        }
	
	        /* 获得邮件服务器的参数设置 */
	        $params['host'] = $this->server;
	        $params['port'] = $this->port;
	        $params['user'] = $this->user;
	        $params['pass'] = $this->password;
	
	        if (empty($params['host']) || empty($params['port']))
	        {
	            // 如果没有设置主机和端口直接返回 false
	            $this->errorlog('SMTP', "($this->server:$this->port)", 0);
	            return false;
	        }
	        else
	        {
	            // 发送邮件
	            if (!function_exists('fsockopen'))
	            {
	                //如果fsockopen被禁用，直接返回
	                $this->errorlog('SMTP', "($this->server:$this->port)", 0);
	
	                return false;
	            }
	
	            include_once(PHPCMS_ROOT . 'include/smtp.class.php');
	            static $smtp;
	
	            $send_params['recipients'] = $email;
	            $send_params['headers']    = $headers;
	            $send_params['from']       = $PHPCMS['mail_user'];
	            $send_params['body']       = $content;
	
	            if (!isset($smtp))
	            {
	                $smtp = new smtp($params);
	            }
	
	            if ($smtp->connect() && $smtp->send($send_params))
	            {
	                return true;
	            }
	            else
	            {
	                $err_msg = $smtp->error_msg();
	                if (empty($err_msg))
	                {
	                    $this->errorlog('SMTP', "(Unknown Error)", 0);
	                }
	                else
	                {
	                    if (strpos($err_msg, 'Failed to connect to server') !== false)
	                    {
	                        $this->errorlog('SMTP', "(Failed to connect to server)", 0);
	                    }
	                    else if (strpos($err_msg, 'AUTH command failed') !== false)
	                    {
	                        $this->errorlog('SMTP', "(AUTH command failed)", 0);
	                    }
	                    elseif (strpos($err_msg, 'bad sequence of commands') !== false)
	                    {
	                        $this->errorlog('SMTP', "(bad sequence of commands)", 0);
	                    }
	                    else
	                    {
	                        $this->errorlog('SMTP', "($err_msg)", 0);
	                    }
	                }
	
	                return false;
	            }
	        }
	    
	}

	function smtp($email_to, $email_subject, $email_message, $email_from = '', $headers = '')
	{
		if(!$fp = fsockopen($this->server, $this->port, $errno, $errstr, 100))
		{
			$this->errorlog('SMTP', "($this->server:$this->port) CONNECT - Unable to connect to the SMTP server", 0);
			return false;
		}
		stream_set_blocking($fp, true);
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != '220')
		{
			$this->errorlog('SMTP', "$this->server:$this->port CONNECT - $lastmessage", 0);
			return false;
		}
		fputs($fp, "EHLO Phpcms\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 220 && substr($lastmessage, 0, 3) != 250)
		{
			$this->errorlog('SMTP', "($this->server:$this->port) HELO/EHLO - $lastmessage", 0);
			return false;
		}
		while(1)
		{
			if(substr($lastmessage, 3, 1) != '-' || empty($lastmessage))
			{
				break;
			}
			$lastmessage = fgets($fp, 512);
		}
		fputs($fp, "AUTH LOGIN\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 334)
		{
			$this->errorlog('SMTP', "($this->server:$this->port) AUTH LOGIN - $lastmessage", 0);
			return false;
		}
		fputs($fp, base64_encode($this->user)."\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 334)
		{
			$this->errorlog('SMTP', "($this->server:$this->port) USERNAME - $lastmessage", 0);
			return false;
		}
		fputs($fp, base64_encode($this->password)."\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 235)
		{
			$this->errorlog('SMTP', "($this->server:$this->port) PASSWORD - $lastmessage", 0);
			return false;
		}
		fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 250)
		{
			fputs($fp, "MAIL FROM: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $email_from).">\r\n");
			$lastmessage = fgets($fp, 512);
			if(substr($lastmessage, 0, 3) != 250)
			{
				$this->errorlog('SMTP', "($this->server:$this->port) MAIL FROM - $lastmessage", 0);
				return false;
			}
		}
		$email_tos = array();
		$emails = explode(',', $email_to);
		foreach($emails as $touser)
		{
			$touser = trim($touser);
			if($touser) 
			{
				fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser).">\r\n");
				$lastmessage = fgets($fp, 512);
				if(substr($lastmessage, 0, 3) != 250)
				{
					fputs($fp, "RCPT TO: <".preg_replace("/.*\<(.+?)\>.*/", "\\1", $touser).">\r\n");
					$lastmessage = fgets($fp, 512);
					$this->errorlog('SMTP', "($this->server:$this->port) RCPT TO - $lastmessage", 0);
					return false;
				}
			}
		}
		fputs($fp, "DATA\r\n");
		$lastmessage = fgets($fp, 512);
		if(substr($lastmessage, 0, 3) != 354)
		{
			$this->errorlog('SMTP', "($this->server:$this->port) DATA - $lastmessage", 0);
		}
		$headers .= 'Message-ID: <'.gmdate('YmdHs').'.'.substr(md5($email_message.microtime()), 0, 6).rand(100000, 999999).'@'.$_SERVER['HTTP_HOST'].">{$this->delimiter}";
		fputs($fp, "Date: ".gmdate('r')."\r\n");
		fputs($fp, "To: ".$email_to."\r\n");
		fputs($fp, "Subject: ".$email_subject."\r\n");
		fputs($fp, $headers."\r\n");
		fputs($fp, "\r\n\r\n");
		fputs($fp, "$email_message\r\n.\r\n");
		fputs($fp, "QUIT\r\n");
		$lastmessage = fgets($fp, 512);
		//echo $this->type.' - '.$this->server.' - '.$this->port.' - '.$this->user.' - '.$this->password.' - '.$email_to.' - '.$email_subject.' - '.$headers.' - '.$email_message.' - '.substr($lastmessage, 0, 3);
		
		//echo substr($lastmessage, 0, 3);
		//return false;
		
		return true;
	}

	function errorlog($type, $message, $is)
	{
		$this->error[] = array($type, $message, $is);
	}
}
?>